<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import axios from "axios";

const chartRef = ref();
let chartInstance = null;

const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);

  chartInstance.setOption({
    title: {
      text: "性别占比",
      left: "center",
      textStyle: {
        color: "#fff",
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c}人 ({d}%)",
    },
    legend: {
      bottom: 0,
      left: "center",
      textStyle: {
        color: "#fff",
      },
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"], // 环形图效果
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderColor: "#0d1b2a",
          borderWidth: 2,
        },
        label: {
          show: true,
          position: "inside",
          color: "#fff",
        },
        labelLine: {
          show: false,
        },
        data: [], // 初始为空
      },
    ],
  });
};

let showGender = true;

const updateChart = async () => {
  const res = await axios.get("/api/chart/user-distribution");
  if (res.data.code !== 0) return;

  const { gender, region } = res.data.data;

  if (showGender) {
    chartInstance.setOption({
      title: { text: "性别占比" },
      series: [{ data: gender }],
    });
  } else {
    chartInstance.setOption({
      title: { text: "地区占比" },
      series: [{ data: region }],
    });
  }

  showGender = !showGender; // 切换显示类型
};

onMounted(() => {
  initChart();
  updateChart();
  // const timer = setInterval(updateChart, 8000);
  // onBeforeUnmount(() => clearInterval(timer));
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
